package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.PayFlow;
import cn.itsource.ymcc.dto.AlipayNotifyDto;
import cn.itsource.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
@RocketMQMessageListener(topic = BaseConstants.PayMQ.TOPIC_PAY_RESULT,
        selectorExpression=BaseConstants.PayMQ.TAGS_BUYCOURSE_RESULT_2ORDER
        ,consumerGroup = "service-order-pay-reslut-consumer"
        ,messageModel = MessageModel.CLUSTERING
    )
public class BuyCoursePayResultMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public void onMessage(MessageExt message) {
        String msg = new String(message.getBody(), CharsetUtil.UTF_8);
        log.info("订单消费者,处理支付结果收到消息-> {} ",msg);
        AlipayNotifyDto dto = JSON.parseObject(msg, AlipayNotifyDto.class);
        CourseOrder order = courseOrderService.selectByOrderNo(dto.getOut_trade_no());

        //幂等判断,如果是集群需要加分布式锁
        synchronized (order.getOrderNo()){
            //课程订单已经被处理
            if(order.getStatusOrder() != BaseConstants.Order.STATUS_APPLY){
                return;
            }
        }

        //支付结果修改
        if(dto.isTradeSuccess()){
            order.setStatusOrder(BaseConstants.Order.STATUS_COMPLETE);
            order.setUpdateTime(new Date());
        }else{
            order.setStatusOrder(BaseConstants.Order.STATUS_PAY_FAIL);
        }
        courseOrderService.updateById(order);
    }
}
